﻿using Dapper;
using Max.PH6_2006A.LowCode.Domain;
using Max.PH6_2006A.LowCode.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Data;

namespace Max.PH6_2006A.LowCode.API.Controllers
{
    [Route("exam/month")]
    [ApiController]
    public class MonthExamController : ControllerBase
    {
        #region 直接用Dapper的方式

        //IDbConnection _db;
        //IConfiguration _configuration;

        ///// <summary>
        ///// 
        ///// </summary>
        //public MonthExamController(IConfiguration configuration)
        //{
        //    _db = new System.Data.SqlClient.SqlConnection(configuration.GetSection("DatabaseConfig:ConnectionString").Value);//("server=.;database=;uid=sa;pwd=qwe123;");
        //}

        #endregion


        #region 用仓储的方式

        ISystemRoleService _roleService;
        ISystemUserService _userService;
        ISystemMenuService _menuService;
        ISystemUserRoleService _userRoleService;
        ISystemRoleMenuService _roleMenuService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="roleService"></param>
        /// <param name="userService"></param>
        /// <param name="menuService"></param>
        public MonthExamController(ISystemRoleService roleService, ISystemUserService userService, ISystemMenuService menuService,
            ISystemUserRoleService userRoleService, ISystemRoleMenuService roleMenuService)
        {
            _roleService = roleService;
            _userService = userService;
            _menuService = menuService;
            _userRoleService = userRoleService;
            _roleMenuService = roleMenuService;
        }
        #endregion

        /// <summary>
        /// 角色列表显示
        /// </summary>
        /// <returns></returns>
        [HttpGet("role/query")]
        public IActionResult RoleQuery()
        {
            DTO.ApiResultReturnDto dto = new();

            try
            {
                var list = _roleService.Query("select * from SystemRole");
                dto.Data = list;
            }
            catch (Exception ex)
            {
                dto.Code = DTO.ApiResultReturnCode.Failed;
                dto.Message = ex.Message;
            }

            return Ok(dto);
        }


        /// <summary>
        /// 用户列表显示
        /// </summary>
        /// <returns></returns>
        [HttpGet("user/query")]
        public IActionResult UserQuery()
        {
            DTO.ApiResultReturnDto dto = new();

            try
            {
                var list = _roleService.Query("select * from SystemUser");
                dto.Data = list;
            }
            catch (Exception ex)
            {
                dto.Code = DTO.ApiResultReturnCode.Failed;
                dto.Message = ex.Message;
            }

            return Ok(dto);
        }

        /// <summary>
        /// 权限列表显示（这个数据是给前台的树形控件）
        /// </summary>
        /// <returns></returns>
        [HttpGet("menu/query")]
        public IActionResult MenuQuery()
        {
            DTO.ApiResultReturnDto dto = new();

            try
            {
                var list = _roleService.Query("select * from SystemMenu");
                dto.Data = list;
            }
            catch (Exception ex)
            {
                dto.Code = DTO.ApiResultReturnCode.Failed;
                dto.Message = ex.Message;
            }

            return Ok(dto);
        }


        /// <summary>
        /// 根据角色ID，获取该角色对应的用户和菜单，用于显示
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns></returns>
        [HttpGet("role/detail")]
        public IActionResult RoleDetailQuery(string roleId)
        {
            DTO.ApiResultReturnDto dto = new();
            try
            {
                //查询这个角色所有的用户
                string sql = "select b.* from SystemUserRole a " +
                    " left join SystemUser b on a.UserId = b.Id  where a.RoleId=@RoleId";

                var users = _userService.Query(sql, new { RoleId = roleId });

                //查询这个角色所拥有的权限菜单
                sql = "select b.* from SystemRoleMenu a " +
                    " left join SystemMenu b on a.MeunId = b.Id where a.RoleId = @RoleId";

                var menus = _menuService.Query(sql, new { RoleId = roleId });

                dto.Data = new { users, menus };
            }
            catch (Exception ex)
            {
                dto.Code = DTO.ApiResultReturnCode.Failed;
                dto.Message = ex.Message;
            }

            return Ok(dto);
            
        }

        /// <summary>
        /// 修改角色状态
        /// </summary>
        /// <returns></returns>
        [HttpGet("role/update")]
        public IActionResult RoleUpdateStatue(string roleId, string statueValue)
        {
            DTO.ApiResultReturnDto dto = new();

            try
            {
                string sql = "update systemRole set statue=@Statue where id =@Id";
                var result = _roleService.Execute(sql, new { Statue = statueValue, Id = roleId });
                dto.Data = result;
            }
            catch (Exception ex)
            {
                dto.Code = DTO.ApiResultReturnCode.Failed;
                dto.Message = ex.Message;
            }

            return Ok(dto);
        }



        /// <summary>
        /// 添加角色（及角色对应的用户和权限菜单）
        /// </summary>
        /// <returns></returns>
        [HttpPost("role/insert")]
        public IActionResult RoleInsert(MonthExamInsertRoleDto dto)
        {
            DTO.ApiResultReturnDto res = new();
            try
            {

                Dictionary<string, object> keyValues = new Dictionary<string, object>();

                //dto这个参数分别对应角色表、用户角色表、角色菜单表

                Guid roleId = Guid.NewGuid(); //定义一个角色id
                                              //插入角色表sql
                dto.roleInfo.Id = roleId;
                string sql = "insert into SystemRole(Id,Name,Remark) values(@Id,@Name,@Remark)";  //管理员，角色描述
                keyValues.Add(sql, dto.roleInfo);
                //_roleService.Execute(sql, dto.roleInfo);

                /*
                 * 插入数据到其它关联表中，需要角色ID，如何获取？
                 * 1、插入角色的时候，把Id也插入进去
                 *      注意：主键为自增长的时候，Id插入会报错。所以只能用在非自增长的主键id上，如Guid，雪花ID等。。。
                 * 2、对自增长，插入之后，再根据名称去查询一次，就可以获取刚才插入的自增长ID
                 * 3、对自增长，可以直接在插入之后 用select @@identity获取刚插入的自增长ID
                 * **/


                //插入用户角色表sql
                dto.selectedUserInfo.ForEach(x =>
                {
                    x.RoleId = roleId;
                });
                sql = "insert into SystemUserRole(UserId,RoleId) values(@UserId,@RoleId)";  //我选择是1012这个用户 ，UserId =1，roleid=???????????????
                keyValues.Add(sql, dto.selectedUserInfo);
                //_userRoleService.Execute(sql, dto.selectedUserInfo);


                dto.selectedMenuInfo.ForEach(x =>
                {
                    x.RoleId = roleId;
                });
                //插入角色菜单表sql
                sql = "insert into SystemRoleMenu(RoleId,MeunId) values(@RoleId,@MenuId)";  //我选择的是日志管理这个菜单，MenuId=1,roleid=????????????????????
                keyValues.Add(sql, dto.selectedMenuInfo);
                //_roleMenuService.Execute(sql, dto.selectedMenuInfo);

                int result = _roleService.InsertRoleAndUserRoleAndRoleMenu(keyValues).Result;
                res.Data = result;
            }
            catch (Exception ex)
            {
                res.Code = DTO.ApiResultReturnCode.Failed;
                res.Message = ex.Message;
            }

            return Ok(res);
        }
    }

    public class MonthExamInsertRoleDto
    {
        public SystemRole roleInfo { get; set; }
        public List<SystemUserRole> selectedUserInfo { get; set; }
        public List<SystemRoleMenu> selectedMenuInfo { get; set; }
    }
}
